import {formatGMTDate,toPercent,sortBy} from '../../../../assets/js/util.js'
import echarts from 'echarts'
export default {
	data() {
		return {
			pickerOptions0: {
	          disabledDate(time) {
	            return time.getTime() > Date.now() - 8.64e7;
	          }
	        },
			// 默认参数 和 URL
			SRC: '',
			DP: {
				p: '',
                f: '',
                uid:''
            },
            loading: false,
			searchable: false,
			realLoadShow:true,
            ruleForm :{
                sday:'',
                eday:'',
                startDate: '',
                platForm:'0',
                channel: '0',
                server: '0',
                jewel: '2'
            },
			// title
			title: "经济统计",
			xlsxTitle:'',
			ftitle:'',
			/* 的宽*/
			pageWidth: '100%',
			/*第一个table*/
			page1:{
				/*当前页显示数量*/
				pageSize: 10,
				/*每页显示的数量*/
				pageSizes: [10, 20, 50, 100],
				/*dataTotal表数量*/
				dataTotal: 0,
				/*分页器*/
				currentPage: 1,
			},
			page2:{
				/*当前页显示数量*/
				pageSize: 10,
				/*每页显示的数量*/
				pageSizes: [10, 20, 50, 100],
				/*dataTotal表数量*/
				dataTotal: 0,
				/*分页器*/
				currentPage: 1,
			},
			page3:{
				/*当前页显示数量*/
				pageSize: 10,
				/*每页显示的数量*/
				pageSizes: [10, 20, 50, 100],
				/*dataTotal表数量*/
				dataTotal: 0,
				/*分页器*/
				currentPage: 1,
			},
			postObj: {
				value: '0',
				label:'消耗量'
			},
			postObj2: {
				value: '0',
				label:'消耗量'
			},
			// 概览
			tableHeaderAll1: [{prop:'day',label:'日期',width:'auto'},{prop:'platformId',label:'平台',width:'auto'},{prop:'channelId',label:'渠道',width:'auto'},{prop:'serverId',label:'区服',width:'auto'},{prop:'add',label:'产出',width:'auto'},{prop:'plus',label:'消耗',width:'auto'},{prop:'rest',label:'剩余',width:'auto'}],
			tableData1: [],
			tableData1All: [],
			// 货币消耗途径(TOP20)
			tableHeaderAll2: [{prop:'consumeWayStr',label:'消耗途径',width:'auto'},{prop:'consumeCount',label:'消耗量',width:'auto'},{prop:'consumeCountRadio',label:'消耗量占比',width:'auto'},{prop:'consumeUser',label:'消耗人数',width:'auto'},{prop:'consumeUserRadio',label:'消耗人数占比',width:'auto'}	],
			tableData2: [],
			tableData2All:[],
			// 商城道具相关货币消耗途径(TOP20)
			tableHeaderAll3: [{prop:'consumeWayStr',label:'道具名称',width:'auto'},{prop:'consumeCount',label:'消耗量',width:'auto'},{prop:'consumeCountRadio',label:'消耗量占比',width:'auto'},{prop:'consumeUser',label:'消耗人数',width:'auto'},{prop:'consumeUserRadio',label:'消耗人数占比',width:'auto'}],
			tableDat3: [],
			tableData3All:[],
			tableAll:[],

			// 图表数据
			real: {
				// 显示提示框
				tooltip: {
					trigger: 'axis'
				},
				// 图列
				legend: {
					top: '10px',
					data:[]
				},
				// 网格
				grid: {
					left: '1%',
					right: '2%',
					bottom: '15%',
					containLabel: true
				},
				// 工具栏
				toolbox: {
					right: '20',
					feature: {
						dataZoom: {
							yAxisIndex: 'none'
						},
						magicType: {
							type: ['line', 'bar']
						},
						restore: {},
						saveAsImage: {}
					}
				},
				// x轴
				xAxis: {
					type: 'category',
					data: [],
					axisLabel:{
                        margin:20,
                    },
				},
				// y轴
				yAxis:[{
					type: 'value',
					// max: 10000
					axisLabel: {
						show: true,  
                  		interval: 'auto',  
		                formatter: function(val){
		                	//val = toPercent(val);
		                	return val
		                }
		            }
				}] ,
				dataZoom: [{
					handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
					handleSize: '80%',
					handleStyle: {
						color: '#fff',
						shadowBlur: 3,
						shadowColor: 'rgba(0, 0, 0, 0.6)',
						shadowOffsetX: 2,
						shadowOffsetY: 2
					},
            		zoomOnMouseWheel:false
				}],
				series: [{
					name: '1',
					type: 'line',
					data:[],
					symbol:'triangle',
					itemStyle: {
		                normal: {
		                    color: new echarts.graphic.LinearGradient(
		                        0, 0, 0, 1,
		                        [
		                            {offset: 0, color: '#66cf97'},
									{offset: 0.5, color: '#4eb59a'},
									{offset: 1, color: '#349b98'}
		                        ]
		                    )
		                },
		                emphasis: {
		                    color: new echarts.graphic.LinearGradient(
		                        0, 0, 0, 1,
		                        [
		                            {offset: 0, color: '#4eb59a'},
		                            {offset: 0.7, color: '#349b98'},
		                            {offset: 1, color: '#66cf97'}
		                        ]
		                    )
		                }
		            },
				},{
					name: '2',
					type: 'line',
					symbol:'roundRect',
					data:[],
					itemStyle: {
		                normal: {
		                    color: new echarts.graphic.LinearGradient(
		                        0, 0, 0, 1,
		                        [
		                            {offset: 0, color: '#84ebd8'},
									{offset: 0.5, color: '#7fd2e2'},
									{offset: 1, color: '#7abde8'}
		                        ]
		                    )
		                },
		                emphasis: {
		                    color: new echarts.graphic.LinearGradient(
		                        0, 0, 0, 1,
		                        [
		                            {offset: 0, color: '#7abde8'},
		                            {offset: 0.7, color: '#7fd2e2'},
		                            {offset: 1, color: '#84ebd8'}
		                        ]
		                    )
		                }
		            },
				},{
					name: '3',
					type: 'line',
					// symbol:'circle',
					data:[],
					itemStyle: {
		                normal: {
		                    color: new echarts.graphic.LinearGradient(
		                        0, 0, 0, 1,
		                        [
		                            {offset: 0, color: '#b8cff1'},
									{offset: 0.5, color: '#a99ce4'},
									{offset: 1, color: '#a07cdc'}
		                        ]
		                    )
		                },
		                emphasis: {
		                    color: new echarts.graphic.LinearGradient(
		                        0, 0, 0, 1,
		                        [
		                            {offset: 0, color: '#a07cdc'},
		                            {offset: 0.7, color: '#a99ce4'},
		                            {offset: 1, color: '#b8cff1'}
		                        ]
		                    )
		                }
		            },
				}
			
			]
			},
            // 渠道名称
            channels:[],
            chanNum:0,
            // 平台
            platForms:[],
            platNum:0,
            // 钻石
            jewels:[],
            jewNum:2,
            // 全服
            servers:[],
			serNum:0,
			tableIndex:'',
			chartDataA:[{value:0,label:"消耗量"},{value:1,label:"消耗量人数"}],
			sheet:''
		}
	},
	methods: {
        // 初始化时间
        dateChange(val){
            if(val){
                var val = val.split(" ");
                this.sday = val[0];
                this.eday = val[2];
            }
        },
		// 表格下载
	    excel(tableIndex,sheet) {
			this.xlsxTitle = sheet+"-"+this.sday+"到"+this.eday;
            this.downloadExl(this["tableHeaderAll"+tableIndex],this["tableData"+tableIndex+"All"],this.xlsxTitle,sheet);
	    },
		// 通用 成功 与 失败
		successFun(data) {
			this.$message({
				message: data,
				type: 'success'
			});
		},
		errorFun(data) {
			this.$message.error(data);
		},
		// 分页器
		// // 控制每页的数量
		handleSizeChange1(val) {
			this.page1.pageSize = val;
			this.page1.dataTotal = this.tableData1All.length;
			this.tableData1= this.tableData1All.slice((this.page1.currentPage-1)*(this.page1.pageSize),this.page1.currentPage*this.page1.pageSize);
		},
		// 页数
		handleCurrentChange1(val) {
			this.page1.currentPage = val;
			this.page1.dataTotal = this.tableData1All.length;
			this.tableData1= this.tableData1All.slice((this.page1.currentPage-1)*(this.page1.pageSize),this.page1.currentPage*this.page1.pageSize);
		},
		// 控制每页的数量
		handleSizeChange2(val) {
			this.page2.pageSize = val;
			this.page2.dataTotal = this.tableData2All.length;
			this.tableData2= this.tableData2All.slice((this.page2.currentPage-1)*(this.page2.pageSize),this.page2.currentPage*this.page2.pageSize);
		},
		// 页数
		handleCurrentChange2(val) {
			this.page2.currentPage = val;
			this.page2.dataTotal = this.tableData2All.length;
			this.tableData2= this.tableData2All.slice((this.page2.currentPage-1)*(this.page2.pageSize),this.page2.currentPage*this.page2.pageSize);
		},
		// 控制每页的数量
		handleSizeChange3(val) {
			this.page3.pageSize = val;
			this.page3.dataTotal = this.tableData3All.length;
			this.tableData3= this.tableData3All.slice((this.page3.currentPage-1)*(this.page3.pageSize),this.page3.currentPage*this.page3.pageSize);
		},
		// 页数
		handleCurrentChange3(val) {
			this.page3.currentPage = val;
			this.page3.dataTotal = this.tableData3All.length;
			this.tableData3= this.tableData3All.slice((this.page3.currentPage-1)*(this.page3.pageSize),this.page3.currentPage*this.page3.pageSize);
		},
		// 变成分数
		pencent(data,key1,key2) {
			//转换为%比 
			for(var i = 0; i<data.length; i++){
				for(var j in data[i]){
					if(j === key1){
						data[i][j] = toPercent(data[i][j]);
					}
					if(j === key2){
						data[i][j] = toPercent(data[i][j]);
					}
				}
			}
			return data
		},
        loads() {
            this.loading = !this.loading; //加载中
            this.searchable = !this.searchable; //查询按钮不可用
		},
		search(){
			this.apiAjax(this.sday,this.eday)
		},
        channelChange(o){
			this.chanNum = o;
			this.apiAjax1('channel='+o,'updateChannel')
        },
        platChange(o){
			this.platNum = o;
			this.apiAjax1('platform='+o,'updatePlatform')
        },
        serverChange(o){
			this.serNum = o;
			this.apiAjax1('server='+o,'updateServer')
        },
        jewelChange(o){
            this.jewNum = o;
        },
        getJsonarr(objarr){
            var arrNew = [];
            Object.keys(objarr).forEach(function(key){
                var obj = {}
                obj.id = key;
                obj.num = objarr[key];
                arrNew.push(obj)
            })
            return arrNew;
        },
        sortBy1(obj){
            return obj.sort(function(a,b){
                return parseInt(a['num']) - parseInt(b['num'])
            })
        },
        findData (data){
            this.sday = formatGMTDate(new Date(new Date().getTime() - 1000*60*60*24*8),true,true);
            this.eday = formatGMTDate(new Date(new Date().getTime() - 1000*60*60*24*1),true,true);
            this.ruleForm.startDate = [this.sday,this.eday];
            this.loads();
            this.apiAjax(this.sday,this.eday)
		},
		apiAjax1(keyV,aDo){
			this.$http.jsonp(`${this.SRC}data/get.do?p=${this.DP.p}&f=${this.DP.f}&a=${aDo}`,{
                params: {'ps':keyV}
            }).then(function(res){
				var data =  JSON.parse(JSON.parse(res.body));
				if(data.res == "0"){
					if(aDo == 'updateServer'){
						this.platForms =this.sortBy1(this.getJsonarr(data.platformItmes));
						this.channels = this.sortBy1(this.getJsonarr(data.channelItmes));
					}else if(aDo == 'updateChannel'){
						this.platForms =this.sortBy1(this.getJsonarr(data.platformItmes));
						this.servers = this.sortBy1(this.getJsonarr(data.serverItmes));
					}else if(aDo == 'updatePlatform'){
						this.channels = this.sortBy1(this.getJsonarr(data.channelItmes));						
						this.servers = this.sortBy1(this.getJsonarr(data.serverItmes));
					}				
                }else{
                	this.errorFun(data['msg'])
                }
            }).catch(function(res){})
		},
        apiAjax(sday,eday){
            this.$http.jsonp(`${this.SRC}data/get.do?p=${this.DP.p}&f=${this.DP.f}&a=search`,{
                params: {'ps':`dstart=${sday}&dend=${eday}&platform=${this.platNum}&channel=${this.chanNum}&server=${this.serNum}&curType=${this.jewNum}`}
            }).then(function(res){
                this.loads();
				var data = JSON.parse(JSON.parse(res.body).replace(/\"\{\"/g, '\{\"').replace(/\"\}\"/g, '\"\}'));
                if(parseInt(data['res']) === 0){
					this.tableData1All = data.yuanbaoSumDatas;
					this.tableData2All = this.pencent(data.yuanbaoConsumeData,'consumeCountRadio','consumeUserRadio');
					this.tableData3All = this.pencent(data.shangchengConsumeDatas,'consumeCountRadio','consumeUserRadio');
					data['yuanbaoConsumeChart']['jsonStr'].columnkeys.reverse();
					data['yuanbaoConsumeChart']['jsonStr'].data[0].reverse();
					data['yuanbaoConsumeChart1']['jsonStr'].columnkeys.reverse();
					data['yuanbaoConsumeChart1']['jsonStr'].data[0].reverse();
					data['shangchengConsumeChart']['jsonStr'].columnkeys.reverse();
					data['shangchengConsumeChart']['jsonStr'].data[0].reverse();
					data['shangchengConsumeChart1']['jsonStr'].columnkeys.reverse();
					data['shangchengConsumeChart1']['jsonStr'].data[0].reverse();
					this.echartsData(data);
					this.page1.dataTotal = this.tableData1All.length;
					this.page2.dataTotal = this.tableData2All.length;
					this.page3.dataTotal = this.tableData3All.length;

					this.tableData1= this.tableData1All.slice((this.page1.currentPage-1)*(this.page1.pageSize),this.page1.currentPage*this.page1.pageSize);
					this.tableData2= this.tableData2All.slice((this.page2.currentPage-1)*(this.page2.pageSize),this.page2.currentPage*this.page2.pageSize);
					this.tableData3= this.tableData3All.slice((this.page3.currentPage-1)*(this.page3.pageSize),this.page3.currentPage*this.page3.pageSize);


					this.tableAll = data;
                }else{
                    this.errorFun(data['msg'])
                }
            }).catch(function(res){})
        },
        getData(){
            this.$http.jsonp(`${this.SRC}data/get.do?p=${this.DP.p}&f=${this.DP.f}&a=initParam`,{
                params: {'ps':''}
            }).then(function(res){
                var data =  JSON.parse(JSON.parse(res.body));
                if(data.res == "0"){
                    this.platForms =this.sortBy1(this.getJsonarr(data.platformItmes));
                    this.servers = this.sortBy1(this.getJsonarr(data.serverItmes));
                    this.jewels = this.sortBy1(this.getJsonarr(data.yuabaoItmes));
                    this.channels = this.sortBy1(this.getJsonarr(data.channelItmes));
                }else{
                	this.errorFun(data['msg'])
                }
            }).catch(function(res){
                console.log(res)
            })
		},
		//初始化
		// 设置图表初始化宽度
		chartsWidth (el){
			if(document.getElementById(el)!==null){
				document.getElementById(el).style.width = window.innerWidth-272+"px";
			}
		},
		_init() {
			var arr = ['realTimeData','realTimeData2','realTimeData3'];
			for(var x=0; x<arr.length;x++){
				this.chartsWidth(arr[x]);
				this[arr[x]+'Chart'] = echarts.init(document.getElementById(arr[x]));
				this[arr[x]+'Chart'].setOption(this.real);
			}
			window.addEventListener('resize', function() {
				for(var i in arr){
					this.chartsWidth(arr[i])
				}
				var resizeArr = ['realTimeDataChart','realTimeData2Chart','realTimeData3Chart']
				for(var j in resizeArr){
					this[resizeArr[j]].resize();
				}
			}.bind(this))
		},
		postObjFn(o){	
			this.echartsData2(o,2)
		},
		postObjFn2(o){
			this.echartsData2(o,3)
		},
		// 获取表数据
		echartsData(d,o) {
			this.realLoadShow = false;	
			if(d.yuanbaoSumChart === undefined){
				var data = {
					"columnkeys":[],
					"names":[],
					"data":[[]]
				}
			}else{
				var data = d['yuanbaoSumChart']['jsonStr'];
			}
			this.realTimeDataChart.setOption({
				legend: {
					data: data['names']
				},
				xAxis: {
					data: data.columnkeys
				},
				series: [
					{
						name: data.names[0],
						data: data.data[0],
						smooth: true,
					},
					{
						name: data.names[1],
						data: data.data[1],
						smooth: true,
					},
					{
						name: data.names[2],
						data: data.data[2],
						smooth: true,
					}
				]
			});
			if(d.yuanbaoConsumeChart === undefined){
				var data = {
					"columnkeys":[],
					"names":[],
					"data":[[]]
				}
			}else{
				var data = d['yuanbaoConsumeChart']['jsonStr'];
				this.sheet = "消耗量";
			}
			this.realTimeData2Chart.setOption({
				tooltip : {
					trigger: 'axis'
				},
				legend: {
					data:data['names']
				},
				xAxis : [
					{
						type : 'value',
						splitNumber:data.columnkeys.length,
						axisLabel: {
							show: true,  
							interval: 'auto',  
							formatter: function(val){
								val = val/1000;
								return val+'k'
							}
						}
					}
				],
				yAxis : [
					{
						type : 'category',
						data : data.columnkeys
					}
				],
				series : [
					{
						name:data.names[0],
						type:'bar',
						data:data.data[0],
						barWidth:10
					}
				],
				dataZoom: [{
					start: 0,
            		zoomOnMouseWheel:false
				}],
				itemStyle:{
					normal:{
						color:'#2f7ed8',
					}
				}

			});	
			if(d.shangchengConsumeChart === undefined){
				var data = {
					"columnkeys":[],
					"names":[],
					"data":[[]]
				}
			}else{
				var data = d['shangchengConsumeChart']['jsonStr'];
				this.sheet = "消耗量";
			}
			this.realTimeData3Chart.setOption({
				tooltip : {
					trigger: 'axis'
				},
				legend: {
					data:data['names']
				},
				xAxis : [
					{
						type : 'value',
						splitNumber:data.columnkeys.length,
						axisLabel: {
							show: true,  
							interval: 'auto',  
							formatter: function(val){
								val = val/1000;
								return val+'k'
							}
						}
					}
				],
				yAxis : [
					{
						type : 'category',
						data : data.columnkeys
					}
				],
				series : [
					{
						name:data.names[0],
						type:'bar',
						data:data.data[0],
						barWidth:10
					}
				],
				dataZoom: [{
					start: 0,
            		zoomOnMouseWheel:false
				}],
				itemStyle:{
					normal:{
						color:'#2f7ed8',
					}
				}
			});				
		},
		// 改变表数据
		echartsData2(o,n) {
			this.sheet = "消耗量人数";
			this.realLoadShow = false;
			var dd,d;
			if(n==2){
				if(o==1){
					d = 'yuanbaoConsumeChart1'
				}else{
					d = 'yuanbaoConsumeChart'
				}
				var ddd = this.realTimeData2Chart;
			}else{
				if(o==1){
					d = 'shangchengConsumeChart1'
				}else{
					d = 'shangchengConsumeChart'
				}
				var ddd = this.realTimeData3Chart;
			}

			if(this.tableAll[d] === undefined){
				var data = {
					"columnkeys":[],
					"names":[],
					"data":[[]]
				}
			}else{
				var data = this.tableAll[d]['jsonStr'];
			}


			ddd.setOption({
				tooltip : {
					trigger: 'axis'
				},
				legend: {
					data:data['names']
				},
				xAxis : [
					{
						type : 'value',
						splitNumber:data.columnkeys.length,
						axisLabel: {
							show: true,  
							interval: 'auto',  
							formatter: function(val){
								val = val/1000;
								return val+'k'
							}
						}
					}
				],
				yAxis : [
					{
						type : 'category',
						data : data.columnkeys
					}
				],
				series : [
					{
						name:data.names[0],
						type:'bar',
						data:data.data[0],
						barWidth:10
					}
				],
				dataZoom: [{
					start: 0,
            		zoomOnMouseWheel:false
				}],
				itemStyle:{
					normal:{
						color:'#2f7ed8',
					}
				}

			});			
		},
	},
	computed:{
		// xlsx(){
		//   return this.title+'.xlsx'
		// }
	},
	mounted() {
		// 初始化echart
		this._init();
		// 初始化URL
		this.SRC = this.$store.getters.src;
        this.DP.p = localStorage.getItem('ZULONGBIPROJECTID');
        this.DP.f = localStorage.getItem('ZULONGBIPAGEID');
        this.DP.uid = localStorage.getItem('ZULONGBIUSERID');
		// 获取到服务器 平台 渠道 钻石
		this.getData();
        this.findData(0)
	}
}